package com.xiaoyu.cloudmusic.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.xiaoyu.cloudmusic.data.GlobalData;
import com.xiaoyu.cloudmusic.pojo.Account;
import com.xiaoyu.cloudmusic.pojo.PlayListDetail;
import com.xiaoyu.cloudmusic.pojo.UserInfo;
import com.xiaoyu.cloudmusic.resp.Login;
import com.xiaoyu.cloudmusic.resp.Payload;
import com.xiaoyu.cloudmusic.resp.PlayList;
import com.xiaoyu.cloudmusic.service.AccountsServiceImpl;
import com.xiaoyu.cloudmusic.service.AdminService;
import com.xiaoyu.cloudmusic.utils.DataUtil;
import com.xiaoyu.cloudmusic.utils.JWTUtils;
import com.xiaoyu.cloudmusic.utils.Result;
import com.xiaoyu.cloudmusic.utils.UID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AccountsController {
    @Autowired
    AccountsServiceImpl accountsService;
    @Autowired
    AdminService adminService;
    //登录
    @RequestMapping("/login/account")
    @ResponseBody
    public Login dologin(Account account){
        System.out.println(account);
        //进行数据库的数据查询，去accounts表中匹配查询
        Account account1= accountsService.findOne(account.getAccount(), account.getPassword());
        Login login=new Login();
        if(account1!=null){//查到了
            login.setCode(200);
            login.setName(account1.getAccount());
            login.setMsg("登录成功！");
            Map<String,String> payload = new HashMap<>();
            payload.put("uuid",account1.getUuid());
            payload.put("account",account1.getAccount());
            /**
             * 登录日志存库
             */
            adminService.log_login(account1.getUuid(),account.getAccount(), DataUtil.getFormatter("yyyy-MM-dd : HH:mm:ss"),"成功");
            //生成JWT令牌
            String token = JWTUtils.getToken(payload);
            login.setToken(token);
        }else{
            login.setCode(401);
            login.setName("XXX");
            login.setMsg("登录失败！请检查账号密码是否正确");
        }
        /**
         * 统计总访问量
         */
        GlobalData.visitCount++;

        return login;
    }

    //注册
    @RequestMapping("/login/regisHandle")
    @ResponseBody
    public Result register(@RequestBody Account account){
        //向数据库中插入数据，前端已经判读过有数据了,前端MD5数据加密过了
        try {
            //这里生成一个UUID存进去。
            String uuid= UID.getUUID();
            accountsService.addAccount(account.getAccount(),account.getPassword(),uuid);
            //这里同时要根据用户的UUID来生成userinfo这条记录
            UserInfo userInfo=new UserInfo();
            userInfo.setUuid(uuid);
            userInfo.setNickname("云听用户");
            userInfo.setPhotoPath("http://localhost:8080/api/avatar/Avatar.jpeg");
            accountsService.addUserInfo(userInfo);
        }catch (Exception e){
            Throwable cause=e.getCause();
            if(cause instanceof SQLIntegrityConstraintViolationException){
                return Result.error(409,"用户名重复");
            }
        }
        return Result.ok("注册成功！");
    }
    //登出
    @RequestMapping("/login/logout")
    @ResponseBody
    public Result logout(){
        //后续如果要做什么可以在这里更改
        return Result.ok();
    }
    //获取用户详细信息
    @RequestMapping("/user/mydetail")
    @ResponseBody
    public Result getUserDetail(@RequestHeader("Authorization") String token) throws JsonProcessingException {
        //Authorization: token,请求带了一个这样的字段,去进行token验证
        //验证成功，去数据库查询响应的用户信息
       Payload payload=JWTUtils.getToken(token);
        //根据payload中的id进行数据库的查询
        UserInfo userInfo=accountsService.getUserInfoByUUID(payload.getUuid());
        return Result.ok().put("data",userInfo);
    }
    //更新用户信息
    @RequestMapping("/user/update")
    @ResponseBody
    public Result upDateUserInfo(UserInfo userInfo,@RequestHeader("Authorization") String token) throws JsonProcessingException {
        //前端拿到修改的数据去数据库进行更新操作(这里也要配合token中带的UUID数据)
        Payload payload=JWTUtils.getToken(token);
        userInfo.setUuid(payload.getUuid());
        try {
           int result= accountsService.upDateUserInfo(userInfo);
           if(result==0)return Result.error(400,"更新失败");
        }catch (Exception e){
            return Result.error(400,"更新失败");
        }
        return new Result();
    }
    //更新头像
    @RequestMapping("/user/photoupload")
    @ResponseBody
    public Result updateAvatar(MultipartFile file, @RequestHeader("Authorization") String token){
        //将前端传来的图片数据传过来保存并生成图片路径。
        String filepath="e:/images/avatar";
        File file1=new File(filepath);
        try {
            String imgName=UID.getUUID() +file.getOriginalFilename();
            file.transferTo(new File(file1, imgName));
            //生成图片路径
            String photoPath="http://localhost:8080/api/avatar/"+imgName;
            Payload payload=JWTUtils.getToken(token);
            //在更新前先将静态资源的图片数据删了
            UserInfo userInfo=accountsService.findUserInfoByUUID(payload.getUuid());
           if(userInfo.getPhotoPath()!=null ){//如果之前没有图片路径存入新的！！
               String oldPhotoPath= userInfo.getPhotoPath();
               String str=oldPhotoPath.replace("http://localhost:8080/api/avatar","");
               File file2=new File(filepath+str);
               if(file2.delete()) {
                   System.out.println("图片删除成功！");
               } else {
                   System.out.println("图片删除失败。请检查路径是否正确，或者是否有足够的权限删除文件。");
               }
           }
            //将路径存入数据库
            accountsService.updateAvatar(photoPath,payload.getUuid());
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        return Result.ok();
    }
    //获取用户歌单
    @RequestMapping("/playList/myplayList")
    @ResponseBody
    public Result getUserPlayList(@RequestHeader("Authorization") String token) throws JsonProcessingException {
        //获取获取歌单列表
        Payload payload=JWTUtils.getToken(token);
        List<PlayListDetail> list=accountsService.getUserPlayList(payload.getUuid());
        List<PlayList> playList=new ArrayList<>() ;
        for(PlayListDetail p:list){
            PlayList playList1=new PlayList();
            playList1.setId(p.getListId());
            playList1.setName(p.getName());
            playList1.setPicUrl(p.getCoverImgUrl());
            playList.add(playList1);
        }
        return Result.ok().put("playList",playList);
    }
}
